package com.fzj.example.thread.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;

/**
 * ClassName: ForkJoinTaskDemo
 * date: 2019/11/6 16:36
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class ForkJoinTaskDemo {

    static class SumTask extends RecursiveTask<Integer>{

        private final int threshold=10;
        private int arr[];
        private int start;
        private int end;

        public SumTask(int[] arr, int start, int end) {
            this.arr = arr;
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            if(end-start<=threshold){
                return sum(start,end);
            }else{
                int middle=(start+end)/2;
                SumTask left=new SumTask(arr,start,middle);
                SumTask right=new SumTask(arr,middle,end);
                left.fork();
                right.fork();
                return left.join() + right.join();
            }
        }

        private Integer sum(int start, int end) {
            int sum=0;
            for(int i=start;i<end;i++){
                sum+=arr[i];
            }
            System.out.println(Thread.currentThread().getName() + ": ∑(" + start + "~" + end + ")=" + sum);
            return sum;
        }
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        int arr[] =new int[1000];
        for(int i=1;i<=1000;i++){
            arr[i-1]=i;
        }
        ForkJoinTask<Integer> forkJoinTask=forkJoinPool.submit(new SumTask(arr,0,arr.length));
        System.out.println("求和结果"+forkJoinTask.invoke());
        System.out.println("求和结果"+forkJoinTask.join());

    }

}
